/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import React from 'react';
import clsx from 'clsx';
import Link from '@docusaurus/Link';
import Heading from '@theme/Heading';
import styles from './styles.module.css';

import {Tags, TagList, type TagType} from '@site/src/data/tags';
import {sortBy} from '@site/src/utils/jsUtils';


function TagItem({
  label,
  description,
  color,
}: {
  label: string;
  description: string;
  color: string;
}) {
  return (
    <li className={styles.tag} title={description}>
      <span className={styles.textLabel}>{label.toLowerCase()}</span>
      <span className={styles.colorLabel} style={{backgroundColor: color}} />
    </li>
  );
}

function ShowcaseCardTag({tags}: {tags: TagType[]}) {
  const tagObjects = tags.map((tag) => ({tag, ...Tags[tag]}));

  // Keep same order for all tags
  const tagObjectsSorted = sortBy(tagObjects, (tagObject) =>
    TagList.indexOf(tagObject.tag),
  );

  return (
    <>
      {tagObjectsSorted.map((tagObject) => {
        return <TagItem {...tagObject} />;
      })}
    </>
  );
}


function ShowcaseCard({item}: any) {
  const {
    title,
    image,
    text,
    href,
    tags,
    source,
  } = item;

  return (
    <li className="card shadow--md">
      <div className={clsx('card__image', styles.showcaseCardImage)}>
        <div style={{backgroundSize: 'cover', backgroundRepeat: 'no-repeat', position: 'relative'}}>
          <img width="640px" height="320px" src={image} />
        </div>
      </div>
      <div className="card__body">
        <div className={clsx(styles.showcaseCardHeader)}>
          <Heading as="h4" className={styles.showcaseCardTitle}>
            <Link href={href} className={styles.showcaseCardLink}>
              {title}
            </Link>
          </Heading>
          {source && (
            <Link
              href={source}
              className={clsx(
                'button button--secondary button--sm',
                styles.showcaseCardSrcBtn,
              )}>
              前往查看
            </Link>
          )}
        </div>
        <p className={styles.showcaseCardBody}>{text}</p>
      </div>
      <ul className={clsx('card__footer', styles.cardFooter)}>
          <ShowcaseCardTag tags={tags} />
        </ul>
    </li>
  );
}

export default React.memo(ShowcaseCard);
